<template>
	<view style="width: 100%;" class="input">
		<!-- <view class="active"> -->
		<!-- 	<view class="active-item" v-for="(item,index) in MomentsType" v-bind:class="[index==opCard_stic?'sticStyle':'']"
			 @click="handldTabList(item,index)">{{item.value}}</view> -->
			 <liuyuno-tabs :tabData="arrtype" :defaultIndex="opCard_stic" @tabClick='tabClick'  v-if="arrtype"/>
		<!-- </view> -->

		<view id="moments">
			<view class="moments__post" v-for="(post,index) in posts" :key="index" :id="'post-'+index">
				<view class="deltext">
					<image src="/static/images/shanc.png" style="width: 26px;height: 28px;" @click="hanldelclick(post)" v-if="post.uid==userInfo.id"></image>
				</view>
				<view class="post-left">
					<image class="post_header" :src="post.user.avatar"></image>
				</view>

				<view class="post_right">
					<view>
						<text class="post-username">{{post.user.nickname}}</text>
						<view id="paragraph" class="paragraph">{{post.content}}</view>
					</view>
					<!-- 相册 -->
					<view>
						<view class="thumbnails" v-if="post.atlas.length">
							<view class="my-gallery" v-for="(image, index_images) in post.atlas" :key="index_images" v-if="post.atlas.length===1">
								<image class="gallery_img" lazy-load mode="aspectFill" :src="image" :data-src="image" @tap.stop="previewImage(post.atlas,image)"></image>
								<view>{{post.atlas.length===1}}</view>
							</view>

							<view class="thumbnail" v-for="(image, index_images) in post.atlas" :key="index_images" v-if="post.atlas.length!==1">
								<image class="gallery_img" lazy-load mode="aspectFill" :src="image" :data-src="image" @tap.stop="previewImage(post.atlas,image)"></image>
								<view>{{post.atlas.length===1}}</view>
							</view>

						</view>
					</view>

					<!-- 资料条 -->
					<view class="toolbar">
						<view class="timestamp">{{post.min}}</view>
						<view class="pinglun">
							<view class="like" @tap="like(index,post.id)">
								<image :src="post.star_list.isStar==0?'/static/images/dianzan_hei.png':'/static/images/dianzan_lan.png'"></image>
								<text style="padding-left: 5px;">点赞</text>
							</view>
							<view class="comment" @tap="commentkk(index,post)">
								<image src="/static/images/pinlun_hei.png"></image>
								<text style="padding-left: 5px;">评论</text>
							</view>
						</view>
					</view>
					<!-- 赞／评论区 -->
					<view class="post-footer">
						<view class="footer_content" v-if="isEmpty(post.star_list.list)">
							<image class="liked" src="/static/images/dianzan_lan.png"></image>
							<text class="nickname" v-if="user" v-for="(user,index_like) in post.star_list.list" :key="index_like">
								{{user}}
								<text v-if="getEnd(post.star_list.list) != index_like">,</text>
							</text>
						</view>

						<view v-if="isEmpty(post.message_list)">
							<view class="footer_content" v-for="(comment,comment_index) in post.message_list" :key="comment_index" @tap="commentkk(index,post,comment.owner_id,comment.owner_nickname)">
								<view style="width: 25px;">
									<image class="liked" src="/static/images/pinlun_lan.png" v-if="comment_index==0"></image>
								</view>
								<!-- 有回复 -->
								<text class="comment-nickname" v-if="comment.from_id">
									{{comment.owner_nickname}}<text class="comment-content">回复</text>{{comment.from_nickname}}: <text class="comment-content">{{comment.message}}</text>
								</text>
								<!-- 没回复 -->
								<text class="comment-nickname" v-else>
									{{comment.owner_nickname}}: <text class="comment-content">{{comment.message}}</text>
								</text>
							</view>
						</view>
					</view>
				</view>
				<!-- 结束 post -->
			</view>
			<uni-load-more :status="loadStatus"></uni-load-more>

			<view class="foot" v-if="showInput">
				<chat-input @send-message="send_comment" @blur="blur" :focus="focus" :placeholder="input_placeholder"></chat-input>
			</view>
			<view class="uni-loadmore" v-if="showLoadMore">{{loadMoreText}}</view>

			<!--发布-->
			<view class="fabu" @click="hanldToPublish()">
				<image src="../../static/images/ad.png"></image>
				<view style="font-weight: bold;">发布</view>
			</view>
		</view>

		<!--授权弹框-->
		<view class="search-body">
			<view class="dialog-container" v-if="tokenShow">
				<view class="dialog-mask"></view>
				<view class="dialog-info">
					<view class="dialog-title">您还未授权</view>
					<view class="dialog-content">请先授权再进行操作</view>
					<view class="dialog-footer">
						<button @click="dontLogin()" class="dialog-btn">暂不登录</button>
						<button @getuserinfo="getLogin" open-type="getUserInfo" class="dialog-btn" style="background-color:#FF5F49;color: #fff;">立即授权</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	//
	import uniLoadMore from "@/components/uni-load-more/uni-load-more.vue"

	import chatInput from '../../components/im-chat/chatinput.vue'; //input框
	import postData from '../../common/index/index.post.data.js'; //朋友圈数据

	import liuyunoTabs from "@/components/liuyuno-tabs/liuyuno-tabs.vue";
	export default {
		components: {
			chatInput,
			uniLoadMore,
			liuyunoTabs
		},
		data() {
			return {
				opCard_stic: 0,
				tabList: ['书画社', '艺术会', '设享会', '歌舞团', '爱美会', '书法社'],

				posts: '', //模拟数据
				user_id: 4,
				username: 'Liuxy',

				index: '',
				comment_index: '',

				input_placeholder: '评论', //占位内容
				focus: false, //是否自动聚焦输入框
				is_reply: false, //回复还是评论
				showInput: false, //评论输入框

				screenHeight: '', //屏幕高度(系统)
				platform: '',
				windowHeight: '', //可用窗口高度(不计入软键盘)

				loadMoreText: "加载中...",
				showLoadMore: false,
				MomentsType: '', //类型
				monType: '', //id
				loadStatus: 'more',
				page: 1,
				comment: '',
				from: 0,
				from_nickname: '',
				token: "",
				tokenShow: "",
				userInfo: "",
				nickname: "",
				avatar: "",
				type: 1,
				
				
				defaultIndex: 6,
				tabsHeight: 0,
				tabs: [
					{
						state: -1,
						text: '全部',
					},
					{
						state: 1,
						text: '测试'
					},
					{
						state: 2,
						text: '测试宽度'
					},
					{
						state: 3,
						text: '测试宽度三号'
					},
					{
						state: 4,
						text: '测试宽度四号小星星'
					},
					{
						state: 5,
						text: '测试宽度五号'
					},
					{
						state: 6,
						text: '测试宽度六号'
					},
				],
				arrtype:""
			}
		},

		onLoad(options) {
			console.log(options)
			if (this.isEmpty(options)) {
				this.monType = options.monType;
			}

			if (this.monType) {
				this.getmomentsList()
				this.opCard_stic = options.index;
			}
			uni.getSystemInfo({ //获取设备信息
				success: (res) => {
					this.screenHeight = res.screenHeight;
					this.platform = res.platform;
				}
			});
			uni.startPullDownRefresh();
			this.getMomentsType(options);

		},
		onShow() {
			this.token = uni.getStorageSync('accessToken');
			if(this.token){
				this.initData()
			}
			uni.onWindowResize((res) => { //监听窗口尺寸变化,窗口尺寸不包括底部导航栏
				if (this.platform === 'ios') {
					this.windowHeight = res.size.windowHeight;
					this.adjust();
				} else {
					if (this.screenHeight - res.size.windowHeight > 60 && this.windowHeight <= res.size.windowHeight) {
						this.windowHeight = res.size.windowHeight;
						this.adjust();
					}
				}
			});
			// this.getmomentsList()
		},
		onHide() {
			// uni.offWindowResize(); //取消监听窗口尺寸变化
		},
		onUnload() {

		},
		onReachBottom() { //监听上拉触底事件
			if (this.loadStatus === 'more' && this.type == 1) {
				console.log("上拉请求", this.monType);
				this.getmomentsList(true)
			}
		},
		onPullDownRefresh() { //监听下拉刷新动作
			console.log('onPullDownRefresh');
			// 这里获取数据
			setTimeout(function() {
				//初始化数据
				uni.stopPullDownRefresh(); //停止下拉刷新
			}, 1000);
		},
		onNavigationBarButtonTap(e) { //监听标题栏点击事件
			if (e.index == 0) {
				this.navigateTo('../publish/publish')
			}
		},
		computed: {

		},

		methods: {
			hanldelclick(post){
				let that = this;
				uni.showModal({
				    title: '提示',
				    content: '您是否确定删除？',
				    success: function (res) {
				        if (res.confirm) {
				            console.log('用户点击确定');
							that.hanldel(post);
				        } else if (res.cancel) {
				            console.log('用户点击取消');
				        }
				    }
				});
			},
			//删除
			hanldel(post){
				this.$http.post('/moments/del', {
					id: post.id
				}).then((response) => {
					const res = response.data;
					if(res.code===0){
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
						this.getmomentsList()
						setTimeout(function(){
							uni.navigateBack()
						}, 1000);
					}
				});
			},
					
			
			dontLogin() {
				this.tokenShow = false
			},
			//友嘉类型
			getMomentsType(options) {
				this.$http.get('/moments/type').then((response) => {
					const res = response.data.data;
					this.monType = this.monType ? this.monType : res[0].id;
					this.MomentsType = res;
					let arr1= JSON.parse(JSON.stringify(this.MomentsType).replace(/value/g,"text"));
					this.arrtype = arr1;
					console.log(this.arrtype )
					if (!this.isEmpty(options)) {
						this.getmomentsList(this.monType)
					}
				})
			},
			getmomentsList(type) {
				if (!type) {
					this.page = 1;
				}
				const params = {
					type: this.monType,
					page: this.page
				}

				this.loadStatus = 'loading'
				this.$http.get('/moments/list', {
					params: params
				}).then((response) => {
					const res = response.data;
					console.log(res)
					if (res.code == 0) {
						if (this.page > res.data.last_page) {
							// 没有数据了
							this.loadStatus = 'noMore'
						} else {
							// 未加载完毕
							this.loadStatus = 'more'
							this.page++
						}
						console.log(type)
						if (type) {
							this.posts = [...this.posts, ...res.data.data];
						} else {
							this.posts = res.data.data
							console.log(this.posts)
							console.log("post")
						}
						this.filter = false
					} else {
						this.filter = false
					}
				})
			},

			//选择tab
			tabClick(item,index) {
				console.log(item)
				console.log(index)
				this.opCard_stic = index;
				this.monType = item.id;
				this.page = 1;
				this.getmomentsList()
			},


			//发布
			hanldToPublish() {
				this.token = uni.getStorageSync('accessToken')
				if (this.token == '') {
					this.tokenShow = true;
				}
				if (this.token) {
					uni.navigateTo({
						url: 'publish'
					})
				}


			},
			test() {
				this.navigateTo('../test/test');
			},
			navigateTo(url) {
				uni.navigateTo({
					url: url
				});
			},

			like(index, id) {

				this.token = uni.getStorageSync('accessToken')

				console.log(this.token)
				console.log("statoken")
				if (this.token == '') {
					this.tokenShow = true;
				}
				if (this.token) {
					let user = uni.getStorageSync('userInfo');
					user = JSON.parse(user);
					console.log(this.posts[index].islike);
					if (this.posts[index].star_list.isStar == 0) {
						this.posts[index].star_list.isStar = 1; // 已点赞

						if (this.isEmpty(this.posts[index].star_list.list)) {
							// this.posts[index].star_list.list[user.id] = ',' + user.nickname;
						} else {
							// this.posts[index].star_list.list[user.id] = user.nickname;
						}
						this.posts[index].star_list.list[user.id] = user.nickname;
					} else {
						this.posts[index].star_list.isStar = 0; // 取消
						delete this.posts[index].star_list.list[user.id];
					}

					console.log(this.posts);
					this.$http.post('/moments/star', {
						id: id
					}).then((response) => {});
				}


			},
			isEmpty(array) {
				for (let i in array) {
					if (i) {
						return true;
					}
				}
				return false;
			},
			commentkk(index, post, from = 0, from_nickname) {
				console.log(this.token + "commentkk")
				this.token = uni.getStorageSync('accessToken')
				if (this.token == '') {
					this.tokenShow = true;
				}
				console.log(this.token + "commentkk")
				if (this.token) {
					console.log(post)
					console.log('回复了:' + from + '_' + from_nickname);
					this.showInput = true; //调起input框
					this.focus = true;
					this.index = index;
					this.post_id = post.id; // 回复的id
					this.from = from;
					this.from_nickname = from_nickname;
				}


			},
			adjust() { //当弹出软键盘发生评论动作时,调整页面位置pageScrollTo
				return;
				uni.createSelectorQuery().selectViewport().scrollOffset(res => {
					var scrollTop = res.scrollTop;
					let view = uni.createSelectorQuery().select("#post-" + this.index);
					view.boundingClientRect(data => {
						console.log("data:" + JSON.stringify(data));
						console.log("手机屏幕高度:" + this.screenHeight);
						console.log("竖直滚动位置" + scrollTop);
						console.log("节点离页面顶部的距离为" + data.top);
						console.log("节点高度为" + data.height);
						console.log("窗口高度为" + this.windowHeight);

						uni.pageScrollTo({
							scrollTop: scrollTop - (this.windowHeight - (data.height + data.top + 45)), //一顿乱算
							// scrollTop: 50, 
							duration: 300
						});
					}).exec();
				}).exec();
			},
			reply(index, comment_index) {
				let token = uni.getStorageSync('accessToken')
				if (this.token == '') {
					this.tokenShow = true;
				}
				if (this.token) {
					console.log('hui')
					this.is_reply = true; //回复中
					this.showInput = true; //调起input框
					let replyTo = this.posts[index].comments.comment[comment_index].username;
					this.input_placeholder = '回复' + replyTo;
					this.index = index; //post索引
					this.comment_index = comment_index; //评论索引
					this.focus = true;
				}


			},
			blur: function() {
				let that = this;
				setTimeout(function() {
					that.init_input();
				}, 100);
			},
			init_input() {
				this.showInput = false;
				this.focus = false;
				this.input_placeholder = '评论';
				this.is_reply = false;
			},
			send_comment: function(message) {
				let token = uni.getStorageSync('accessToken')
				if (token == '') {
					this.tokenShow = true;
				}
				if (token) {
					let user = uni.getStorageSync('userInfo');
					user = JSON.parse(user);

					const param = {
						id: this.post_id,
						owner_nickname: user.nickname, //只是显示
						owner_id: user.id, //只是显示
						from_id: this.from, // 回复了谁
						from: this.from, // 回复了谁
						from_nickname: this.from_nickname, // 回复了谁
						message: message.content
					};
					this.$http.post('/moments/message', param).then((response) => {
						console.log('评论了');
						const res = response.data;
						if (res.code == 0) {
							this.posts[this.index].message_list.push(param);
							console.log(this.posts);
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							});
						}

					});
					this.showInput = false;
					this.init_input();
				}


			},
			previewImage(imgs, img) {
				console.log(img)
				wx.previewImage({
					current: img,
					urls: imgs
				});
			},
			goPublish() {
				uni.navigateTo({
					url: './publish/publish',
					success: res => {},
					fail: () => {},
					complete: () => {}
				});
			},
			getEnd(array) {
				let len = 0;
				for (let i in array) {
					len = i;
				}
				return len;
			},
			//授权
			getLogin() {
				var that = this;
				wx.login({
					//获取code 使用wx.login得到的登陆凭证，用于换取openid==token代替
					success(res) {
						if (res.code) {
							console.log(res.code);
							that.code = res.code;
							//使用 wx.getSetting 获取用户当前的授权状态。
							wx.getSetting({
								success(res) {
									if (res.authSetting['scope.userInfo']) { //已授权=>getUserInfo
										wx.getUserInfo({
											success(res) {
												console.log(res)
												console.log("ressss")
												console.log(that.userinfo)

												const formData = {
													code: that.code,
													avatar: res.userInfo.avatarUrl,
													nickname: res.userInfo.nickName
												}
												that.$http.post('/login/wxLogin', formData).then((response) => {
													const res = response.data;
													console.log(res.data.token);
													if (res.data.token) {
														that.$http.setConfig((config) => { /* 设置全局配置 */
															config.header = {
																...config.header,
																token: res.data.token,
															}
															return config
														})
														wx.setStorageSync("accessToken", res.data.token); //成功之后存入token
													}
													that.initData()
													that.getMomentsType();
													if (that.monType == 1) {
														that.getmomentsList()
													}
													that.tokenShow = false;
													uni.showToast({
														title: res.msg,
														icon: 'none'
													});
												})
											},
											fail(err) {
												console.log(err)
											}
										})
									}
								}
							})
						} else {
							console.log("登录失败！" + res.errMsg);
						}
					}
				});
			},
			initData() {

				let that = this;
				let token = uni.getStorageSync('accessToken')
				console.log('accessToken')
				if (uni.getStorageSync('accessToken')) {
					this.$http.get('/user/info').then((response) => {

						const res = response.data;
						this.userInfo = res.data;
						console.log(this.userInfo);
						console.log("this.userInfo");
						if (this.userInfo.avatar) {
							this.avatar = this.userInfo.avatar;
						}
						// #ifdef  MP-WEIXIN
						uni.getUserInfo({
							provider: 'weixin',
							success: function(res) {
								console.log(res.userInfo);
								that.nickname = res.userInfo.nickName;
								that.avatar = res.userInfo.avatarUrl;
							}
						});
						// #endif
						uni.setStorageSync('userInfo', JSON.stringify(res.data));
					})
				}
			},


		}
	}
</script>

<style scoped>
	@import url("../../common/index/index.css");
.deltext{
		position: absolute;
		right: 10px;
		top: 20px;
		z-index: 9;
	}
.input >>>.tab-box .active {
	font-size: 18px;
	color: #FF5F49;
}
.input>>>.tab-box{
	position: fixed;
	box-shadow:none
}
.input>>>.tab-box .horizontal .underline{
	display: none;
}
	.my-gallery {
		width: 250upx;
		height: 400upx;
		margin: 4upx;
		background: #757575;
		overflow: hidden
	}

	.thumbnail {
		width: 30% !important;
		height: 180upx !important;
		margin: 4upx;
		background: #757575;
		overflow: hidden;
	}

	.active {
		display: -webkit-box;
		display: -webkit-flex;
		display: flex;
		-webkit-box-orient: horizontal;
		-webkit-box-direction: normal;
		-webkit-flex-direction: row;
		flex-direction: row;
		background-color: #fff;
		width: 100%;
		overflow-y: scroll;
		white-space: nowrap;
		height: 30px;
		position: fixed;
		/*  #ifdef H5  */
		top: 44px;
		/*  #endif  */
		/*  #ifdef MP-WEIXIN  */
		top: 0px;
		/*  #endif  */
		z-index: 999;
		align-items: center;
		position: fixed;
	}

	.liked {
		top: 3px;
	}

	.active-item {
		padding: 0 18px;
		font-size: 15px;
		color: #333333;
	}

	.fabu {

		position: fixed;
		z-index: 99;
		bottom: 130px;
		right: 20px;
		border-radius: 50%;
		width: 60px;
		height: 60px;
		background: rgba(255, 95, 73, 1);
		box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.2);
		color: #FFFFFF;
		text-align: center;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

	}

	.fabu image {
		width: 22px;
		height: 22px;
		margin-top: 14upx;

	}

	.pinglun {
		display: flex;
		flex-direction: row;
		width: 160px;
		height: 36px;
		background: rgba(247, 247, 247, 1);
		border-radius: 4px;
		justify-content: space-around;
	}

	#moments .moments__post .like {
		position: inherit;
		right: 0;
	}

	#moments .moments__post .toolbar {
		justify-content: space-between;
	}

	#moments .moments__post .toolbar image {
		padding-left: 0;
		width: 17px;
		height: 17px;
	}

	#moments .moments__post .comment {
		position: inherit;
		right: 0;
	}

	#moments .moments__post .footer_content {
		flex-direction: row;
		align-items: baseline;
		padding-top: 3px;
		background-color: #F7F7F7;
		padding-right: 7px;
		padding-left: 10px;
	}

	#moments .moments__post .footer_content .comment-nickname {
		flex: 1
	}

	.post-footer {
		border-radius: 4px;
	}

	#moments .moments__post .footer_content:nth-of-type(1) {
		border-bottom: 1px solid #EEEEEE;
	}

	.sticStyle {
		font-size: 18px;
		color: #FF5F49;
		font-weight: bold;
	}

	.foot {
		height: 50px;
		min-height: 50px;
		/*  #ifdef  H5  */
		bottom: 50px;
		/*  #endif  */

		/* #ifdef MP-WEIXIN */
		bottom: 0;
		/*  #endif  */
		background-color: #F7F7F7;
	}

	.footer {
		height: 50px;
		min-height: 50px;
		padding: 5px;
	}

	.input>>>.input-text {
		margin-bottom: 10px;
	}

	.input>>>.footer-right {
		padding-bottom: 10px;
	}

	.sticStyle {
		font-size: 18px;
		color: #FF5F49;
		font-weight: bold;
	}

	/*授权*/
	.dialog-mask {
		position: fixed;
		z-index: 1000;
		top: 0;
		right: 0;
		left: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.3);
	}

	.dialog-info {
		position: fixed;
		z-index: 5000;
		width: 80%;
		max-width: 600rpx;
		top: 50%;
		left: 50%;
		-webkit-transform: translate(-50%, -50%);
		transform: translate(-50%, -50%);
		background-color: #ffffff;
		text-align: center;
		overflow: hidden;
	}

	.dialog-title {
		font-size: 36rpx;
		padding: 30rpx 30rpx 10rpx;
	}

	.dialog-content {
		padding: 10rpx 30rpx 20rpx;
		min-height: 80rpx;
		font-size: 32rpx;
		line-height: 1.3;
		word-wrap: break-word;
		word-break: break-all;
		color: #999999;
	}

	.dialog-footer {
		display: flex;
		align-items: center;
		position: relative;
		line-height: 90rpx;
		font-size: 34rpx;
	}

	.dialog-btn {
		display: block;
		-webkit-flex: 1;
		flex: 1;
		position: relative;
		font-size: 16px;
	}

	button {
		background-color: #fff;
		border-radius: 0;
	}

	button::after {
		border-radius: 0;
	}
</style>
